/**
 * Created by admin on 2016/12/7.
 */


let http = require('request-promise');
let jv = require("../libs/sys/myHelper").jv;
let dbr = require("../libs/mysql/mysqlHelper");
const session = require("koa-session2");
const qs = require("querystring");

let setCtx = ctx => {
  ctx.__defineSetter__("msg", function (val) {
    ctx.status = 500;
    // ctx.req.msg = val;
    ctx.set("content-type", "text/plain;charset=utf-8");
    ctx.body = val;
    //ctx.set("msg", encodeURIComponent(val));
  });
  // ctx.__defineGetter__("msg", function () {
  //   return ctx.req && ctx.req.msg;
  // });


  //返回 user.id
  ctx.needLogin = () => {
    if (ctx.session.user && ctx.session.user.id) {
      return ctx.session.user.id;
    }
    ctx.msg = "请登录";
    ctx.set("status", 590);
    return false;
  };
}


let autoLogin = async(ctx) => {
  let token = ctx.req.token;
  if (!token) {
    let cookie = ctx.req.headers["cookie"];
    if (!cookie) return;
    let cookieParts = ctx.req.headers["cookie"].split(";").filter(function (it) {
      return it.trim().startsWith("KTOKEN=")
    });
    if (!cookieParts.length) {
      //如果没有 KTOKEN说明客户端已退出
      ctx.session.user_token = null;
      ctx.session.user = null;
      return;
    }

    token = cookieParts[0].split("=")[1];
  }
  if (!token) return;
  if (ctx.session.user_token == token) return;

  //物业端登录
  if (ctx.req.url.startsWith("/wuye/")) {
    var str = await http.get(app.appConfig.fontHost + "api/user/get", {headers: {token: token}});
    let dataJson = JSON.parse(str);
    let id = dataJson.data && dataJson.data.id;
    if (!id) return;

    let user = await dbr.findOne("select * from sys_user where id=:id", {id: id});
    if (!user) return;

    // return {user: user, token: token};
    ctx.session.user_type = "wuye";
    ctx.session.user = user;
    ctx.session.user_token = token;

    jv.log(`物业用户登录成功，Token:${token} , 用户ID: ${id}, 用户名: ${user.login_name} ,用户手机号: ${user.mobile} , 姓名：${user.name}`);
    return;
  }
  if (ctx.req.url.startsWith("/ayi/")) {
    var str = await http.get(app.appConfig.fontHost + "api/worker/get", {headers: {token: token}});
    let dataJson = JSON.parse(str);
    let id = dataJson.data && dataJson.data.id;
    if (!id) return;

    let user = await dbr.findOne("select * from thwy_worker where id=:id", {id: id});
    if (!user) return;

    // return {user: user, token: token};
    ctx.session.user_type = "ayi";
    ctx.session.user = user;
    ctx.session.user_token = token;

    jv.log(`阿姨用户登录成功，Token:${token} , 用户ID: ${id}, 用户名: ${user.login_name} ,用户手机号: ${user.mobile} , 姓名：${user.name}`);
    return;
  }
  try {
    var str = await http.get(app.appConfig.fontHost + "api/member/get", {headers: {token: token}});
    let dataJson = JSON.parse(str);
    let id = dataJson.data && dataJson.data.id;
    if (!id) return;

    let user = await dbr.findOne("select * from thwy_member where id=:id", {id: id});
    if (!user) return;

    user.name = user.nickname || user.real_name || user.username;

    // return {user: user, token: token};
    ctx.session.user_type = "yezhu";
    ctx.session.user = user;
    ctx.session.user_token = token;

    jv.log(`业主登录成功，Token:${token} , 用户ID: ${id}, 用户名: ${user.username} ,用户手机号: ${user.mobile} , 姓名：${user.name}`);
  }
  catch (e) {
    jv.error(e.message);
  }
}


let setPost = async ctx => {
  if (ctx.method != "POST")  return;

  ctx.req.json = {};
  ctx.body = {};
  await new Promise(function (accept, reject) {
    let postString = "";
    ctx.req.on("data", function (data) {
      postString += data;
    });

    return ctx.req.on("end", function () {
      if (ctx.req.headers["content-type"] == "application/json") {
        if (postString) {
          ctx.req.json = JSON.parse(postString);
        }
      }
      else {
        ctx.req.json = qs.parse(postString);
      }
      accept(ctx.req.json);
    });
  });
}


let setLog = async(ctx, next) => {
  let userName = (ctx.session.user && ctx.session.user.username) || "?";
  jv.log(`--------------------------------------------------------------------------------------------------------------------
${userName}
${ctx.method} ${ctx.url} @${new Date().toString("MM-dd HH:mm:ss")}`);

  const start = new Date();

  try {
    await next();
  }
  catch (er) {
    ctx.set("content-type", "text/html;charset=UTF-8");
    ctx.status = 500;
    ctx.body = `<!DOCTYPE html><html><head><meta charset="UTF-8"><title>${er.message}</title><meta name="viewport" content="width=device-width,initial-scale=1.0,user-scalable=no" /></head><body><p class=main>
${er.message}
</p><pre style='font-size:small;margin:10px;'>
${er.stack}
</pre></body></html>`;

    //记录日志
    if (ctx.method == "POST") {
      jv.log(`请求数据：${JSON.stringify(ctx.req.json)}`);
    }

    jv.log("错误信息：" + er.message);
    jv.log("错误堆栈：" + er.stack);
    return;
  }
  //
  // if (ses) {
  //   ctx.session.user = ses.user;
  //   ctx.session.user_token = ses.token;
  // }
  const ms = new Date() - start;

  //记录日志
  if (ctx.method == "POST") {
    jv.log(`请求数据：${JSON.stringify(ctx.req.json)}`);
  }

  jv.log(`返回状态：${ctx.status} ,用时：${ms}ms`);

  if (ctx.method == "POST") {
    jv.log(`返回数据：${JSON.stringify(ctx.body)}`);
  }
}

exports.init = async(ctx, next) => {
  let url = ""
  if (ctx.req._parsedUrl) {
    url = ctx.req._parsedUrl.pathname;
  }
  else {
    url = ctx.req.url;
    url = url.split("?").slice(0, 1)[0] || "";
  }

  if (url.startsWith("/img")) {
    await next();
    return;
  }

  if (ctx.req.method == "GET") {
    let lastPart = url.split("/").slice(-1)[0].split(".");
    if (lastPart.length > 1) {
      let ext = lastPart.slice(1).slice(-1)[0] || "";
      ext = ext.toLocaleLowerCase();
      if (ext && (["js", "css", "png", "icon", "ico", "jpg", "gif", "html"].indexOf(ext) > -1)) return;
    }
  }

  setCtx(ctx);

  app.pug.locals.url = url;

  await setPost(ctx);
  await  autoLogin(ctx);

  await setLog(ctx, next);
}
